package com.xixiu.theprojectthree.web.controller;

import com.github.pagehelper.PageInfo;
import com.xixiu.theprojectthree.common.entity.Book;
import com.xixiu.theprojectthree.common.entity.Category;
import com.xixiu.theprojectthree.service.BookService;
import com.xixiu.theprojectthree.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author XiXiu
 */
@Controller
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("list.do")
    public String list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, Model model) {
        PageInfo<Book> bookPageInfo = bookService.queryAll(pageNum, pageSize);
        model.addAttribute("pi", bookPageInfo);
        return "list";
    }

    @RequestMapping("toAdd.do")
    public String toAdd() {
        return "add";
    }

    @RequestMapping("toEdit/{id}.do")
    public String toEdit(@PathVariable("id") Integer id, Model model) {
        Book book = bookService.queryById(id);
        model.addAttribute("book", book);
        return "edit";
    }

    @RequestMapping("load.do")
    @ResponseBody
    public List<Category> addLoad() {
        return categoryService.queryAll();
    }

    @RequestMapping("upload.do")
    @ResponseBody
    public String addUpload(@RequestParam("pic") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        String fileName = multipartFile.getOriginalFilename();
        String realPath = request.getServletContext().getRealPath("/picture");
        String path = realPath + "/" + fileName;
        multipartFile.transferTo(new File(path));
        return "picture/" + fileName;
    }


    @PostMapping("insert.do")
    public String insert(Book book, Integer category_id) {
        Category category = new Category();
        category.setCid(category_id);
        book.setCategory(category);
        bookService.insert(book);
        return "redirect:/index.jsp";
    }

    @PutMapping("update.do")
    public String update(Book book, Integer category_id) {
        Category category = new Category();
        category.setCid(category_id);
        book.setCategory(category);
        bookService.update(book);
        return "redirect:/index.jsp";
    }

    @DeleteMapping("delete.do")
    public String delete(Integer id){
        bookService.deleteById(id);
        return "redirect:/index.jsp";
    }
}
